/**
 * HTTP Server Benchmark
 * 
 * This benchmark creates a simple HTTP server that uses actors to process requests,
 * then tests its performance using autocannon.
 */
import { Kameo, ActorRef } from '../src/index';
import { loadConfig } from './config';
import { formatNumber } from './utils';
import autocannon from 'autocannon';

// Define counter messages
interface CounterMessage {
  action: 'increment' | 'get';
  amount?: number;
}

async function main() {
  console.log('🚀 Starting HTTP Server Benchmark');
  
  // Load configuration
  const config = loadConfig({
    // Override defaults
    duration: 10, // seconds
    connections: 100
  });
  
  console.log(`\nBenchmark Configuration:`);
  console.log(`- Duration: ${config.duration} seconds`);
  console.log(`- Connections: ${config.connections}`);
  
  // Initialize Kameo
  console.log('\nInitializing Kameo...');
  const kameo = new Kameo();
  await kameo.init();
  
  // Create a counter actor
  const counterActor = kameo.spawn<CounterMessage, number>('counter', { initialCount: 0 });
  
  // Create a simple HTTP server using Bun
  console.log('\nStarting HTTP server...');
  const server = Bun.serve({
    port: 3000,
    async fetch(req) {
      const url = new URL(req.url);
      
      try {
        // Route: /increment
        if (url.pathname === '/increment') {
          const amount = parseInt(url.searchParams.get('amount') || '1');
          await counterActor.tell({ action: 'increment', amount });
          return new Response('OK');
        }
        
        // Route: /get
        if (url.pathname === '/get') {
          const count = await counterActor.ask({ action: 'get' });
          return new Response(count.toString());
        }
        
        // Default route
        return new Response('Not Found', { status: 404 });
      } catch (error) {
        console.error('Error handling request:', error);
        return new Response('Internal Server Error', { status: 500 });
      }
    }
  });
  
  console.log(`Server listening on http://localhost:${server.port}`);
  
  // Wait for the server to start
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  // Run the benchmark using autocannon
  console.log('\nRunning HTTP benchmark...');
  
  const incrementResult = await autocannon({
    url: 'http://localhost:3000/increment',
    connections: config.connections,
    duration: config.duration,
    title: 'Increment Endpoint'
  });
  
  console.log('\n📊 Increment Endpoint Results:');
  console.log(`- Requests/sec: ${formatNumber(incrementResult.requests.average)}`);
  console.log(`- Latency (avg): ${formatNumber(incrementResult.latency.average, 'ms')}`);
  console.log(`- Latency (p99): ${formatNumber(incrementResult.latency.p99, 'ms')}`);
  
  const getResult = await autocannon({
    url: 'http://localhost:3000/get',
    connections: config.connections,
    duration: config.duration,
    title: 'Get Endpoint'
  });
  
  console.log('\n📊 Get Endpoint Results:');
  console.log(`- Requests/sec: ${formatNumber(getResult.requests.average)}`);
  console.log(`- Latency (avg): ${formatNumber(getResult.latency.average, 'ms')}`);
  console.log(`- Latency (p99): ${formatNumber(getResult.latency.p99, 'ms')}`);
  
  // Cleanup and exit
  console.log('\nShutting down server...');
  server.stop();
  
  console.log('\nBenchmark complete!');
}

main().catch(error => {
  console.error('Benchmark failed:', error);
  process.exit(1);
}); 